<script setup lang="ts">
import { request } from '@/api';
import b64toBlob from 'b64-to-blob';
import { closeToast, showLoadingToast, showSuccessToast, showToast, type ActionSheetAction } from 'vant';
import { onMounted, ref } from 'vue';

// 修改头像
// 控制头像是否显示
const showAvatarSheet = ref(false)
// 选项
const changAvatarActions = [
  { name: '拍照' },
  { name: '相册' },
]
// 打开相机/相册
const onSelectAvatarAction = async (item: ActionSheetAction, index: number) => {
  if (index === 0) {
    // 相册上传
    console.log('拍照上传');
    const data = await mk.pickerCamera()
    // console.log('拍照上传', data)
    updateAvatar(data)
  } else if (index === 1) {
    // 拍照上传
    console.log('相册上传');
    const data = await mk.pickerPhoto()
    // console.log('相册上传', data)
    updateAvatar(data)
  }
}

/* 
  先去看看图片修改接口
  1.查看相册以及拍照返回的格式 -> base64
  2.将base64转换为二进制图片数据
  3.创建一个formdata对象
  4.将二进制数据添加到formdata中
  5.根据接口文档，实现上传
  6.渲染页面中的图片组件
  7.优化
    1.添加loading效果
    2.更新原生侧的用户头像信息
*/
const updateAvatar = async (data: string) => {
  try {
    showLoadingToast({
      message: '正在上传...',
      forbidClick: true,
      duration: 0 // 持续时长为0时，弹窗不会关闭
    })
    const image = b64toBlob(data, 'image/jpeg')
    const fd = new FormData()
    fd.append('file', image, Date.now() + '.jpeg')
    const res = await request.post<MkResponse<{ avatar: string }>>('/member/profile/avatar', fd)
    closeToast()
    console.log('---avatar online:' + res.data.result.avatar)
    profile.value.avatar = res.data.result.avatar
    const user = mk.queryUser()
    user.avatar = res.data.result.avatar
    mk.updateUser(user)
    showToast('上传成功')
  } catch (err) {
    showToast('上传失败')
  }
}

// 选择生日弹层
const showBirthdayPopup = ref(false)
// 当前绑定的日期
const birthday = ref(['2020', '10', '09']);
// 确认选中日期
const onConfirmBirthday = () => {
  console.log(birthday.value)
  profile.value.birthday = birthday.value.join('-')
  showBirthdayPopup.value = false
}

// 选择地区
const showLocationPopup = ref(false)
const areaList = ref<AreaColumns>()
onMounted(async () => {
  areaList.value = await mk.getAreaColumns()
})
// 确认选中的地区
// const onConfirmLocation = (data: any) => {
// 形参解构 => 获取实参时直接解构数据，快速获取值
// const onConfirmLocation = ({ selectedValues }: { selectedValues: string[] }) => {
const onConfirmLocation = (data: { selectedValues: number[] }) => {
  // console.log(data.selectedValues) // ['110000', '110100', '110101']
  // 向profile用户信息中新增三个字段参数，为了满足修改用户信息的接口
  profile.value.provinceCode = data.selectedValues[0]
  profile.value.cityCode = data.selectedValues[1]
  profile.value.countyCode = data.selectedValues[2]

  const province = areaList.value?.province_list[data.selectedValues[0]] // 省
  const city = areaList.value?.city_list[data.selectedValues[1]] // 市
  const county = areaList.value?.county_list[data.selectedValues[2]] // 区
  const location = `${province} ${city} ${county}`
  profile.value.fullLocation = location
  // console.log('省市区：' + location)
  showLocationPopup.value = false
}

// 选择职业
const showProfessionPopup = ref(false)
const columns = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' }
]
// 形参解构
const onConfirmProfession = (data: { selectedValues: string[] }) => {
  // console.log(data.selectedValues[0]);
  profile.value.profession = data.selectedValues[0]
  showProfessionPopup.value = false
}

// 获取用户信息
const profile = ref<ProfileInfo>({} as ProfileInfo)
onMounted(async () => {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0 // 持续时长为0时，弹窗不会关闭
  })
  const res = await request.get<MkResponse<ProfileInfo>>('/member/profile')
  // 主动关闭
  closeToast()
  profile.value = res.data.result
  // console.log(profile.value)
  // 生日选择弹层同步用户生日
  birthday.value = profile.value.birthday.split('-')
})

// 保存用户信息
const loading = ref(false)
const onSubmit = async () => {
  loading.value = true
  const res = await request.put<MkResponse<ProfileInfo>>('member/profile', profile.value)
  loading.value = false
  console.log(res.data.result)
  profile.value = res.data.result
  mk.updateUser(res.data.result)
  showSuccessToast('保存成功');
  mk.backward()
}

</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image round width="100" height="100" class="avatar-img" :src="profile.avatar"
        @click="showAvatarSheet = true">
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>
    <van-action-sheet v-model:show="showAvatarSheet" :actions="changAvatarActions" cancel-text="取消"
      @select="onSelectAvatarAction" :style="{ paddingBottom: '20px' }" close-on-click-action />

    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" v-model="profile.account" readonly></van-field>
      <van-field label="昵称" v-model="profile.nickname" placeholder="请输入昵称"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group v-model="profile.gender" :icon-size="16">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field label="生日" v-model="profile.birthday" readonly placeholder="请选择日期"
        @click="showBirthdayPopup = true"></van-field>
      <!-- 生日选择弹层 -->
      <van-popup v-model:show="showBirthdayPopup" position="bottom">
        <van-date-picker v-model="birthday" title="选择日期" :min-date="new Date('1980-01-01')" :max-date="new Date()"
          @cancel="showBirthdayPopup = false" @confirm="onConfirmBirthday" />
      </van-popup>
      <van-field label="所在地" readonly v-model="profile.fullLocation" placeholder="请选择所在地"
        @click="showLocationPopup = true"></van-field>
      <!-- 所在地选择弹层 -->
      <van-popup v-model:show="showLocationPopup" position="bottom">
        <van-area title="选择所在地" :area-list="areaList" @cancel="showLocationPopup = false"
          @confirm="onConfirmLocation" />
      </van-popup>
      <van-field label="职业" v-model="profile.profession" readonly placeholder="请选择职业"
        @click="showProfessionPopup = true"></van-field>
      <!-- 职业选择弹层 -->
      <van-popup v-model:show="showProfessionPopup" position="bottom">
        <van-picker :columns="columns" @confirm="onConfirmProfession" @cancel="showProfessionPopup = false" />
      </van-popup>
    </van-cell-group>

    <div class="submit">
      <van-button :loading="loading" loading-text="保存中..." round block type="primary" @click="onSubmit">
        保存资料
      </van-button>
    </div>
    <van-toast>
    </van-toast>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>